package com.qk.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qk.common.PageResult;
import com.qk.entity.Role;
import com.qk.mapper.RoleMapper;
import com.qk.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Override
    public void addRole(Role role) {
        //1. 设置创建时间和更新时间
        role.setCreateTime(LocalDateTime.now());
        role.setUpdateTime(LocalDateTime.now());
        //2. 调用Mapper层插入数据
        roleMapper.insert(role);
    }

    @Override
    public Role getRoleById(Integer id) {
        return roleMapper.getRoleById(id);
    }

    @Override
    public void updateRole(Role role) {
        //1. 设置更新时间
        role.setUpdateTime(LocalDateTime.now());
        //2. 调用Mapper层更新数据
        roleMapper.updateRole(role);
    }

    @Override
    public void deleteRole(Integer id) {
        roleMapper.deleteRole(id);
    }

    @Override
    public List<Role> getAllRoles() {
        return roleMapper.getAllRoles();
    }

    @Override
    public PageResult<Role> getRoles(String name, String label, int page, int pageSize) {
        // 开始分页
        PageHelper.startPage(page, pageSize);

        // 执行查询
        List<Role> roles = roleMapper.getRoles(name, label);

        // 获取分页信息
        Page<Role> pageInfo = (Page<Role>) roles;

        // 封装成 PageResult 对象
        return new PageResult<>(pageInfo.getTotal(), pageInfo.getResult());
    }
}